﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Configuration;
using System.Net.Mail;
using System.Web.Configuration;
using System.Web.Security;
using nplJobsCommon.Employeer;
using nplJobsBLL.ProcessEmployeer;
using nplJobsCommon.JobSeeker;
using nplJobsBLL.ProcessSelectJobSeeker;
using nplJobsBLL.Common;
using nplJobsDAL.Common;

public partial class ForgotPassword : BasePage // System.Web.UI.Page
{
    protected void btnSubmit_OnClick(object sender, EventArgs e)
    {
        pnlError.Visible = false;
        pnlEmailAddress.Visible = false;
        pnlSuccess.Visible = false;

        bool isSent = false;
        string msg = string.Empty;
        MembershipUser newUser = Membership.GetUser(txtEmailAddress.Text.Trim());
        if (newUser == null)
        {
            msg = "Sorry, there is no account found for this e-mail address!";
        }
        else if (newUser.IsApproved == false)
        {
            msg = "Sorry, this e-mail address is currently not approved.";
        }
        else if (newUser.IsApproved)
        {
            string newGeneratePass = Membership.GeneratePassword(6, 0);
            string resetPwd = newUser.ResetPassword();

            Guid useGuid = newUser.ProviderUserKey != null ? Guid.Parse(newUser.ProviderUserKey.ToString()) : new Guid();

            ProcessTblUserType processTblUserType = new ProcessTblUserType();
            processTblUserType.UserId = useGuid;
            processTblUserType.invoke();
            tblUserType tblUserType = processTblUserType.tblUserType;
            if (tblUserType == null) return;
            if (tblUserType.UserType == 1) //Job Seeker
            {
                JobSeeker jobSeeker = GetJobSeeker(useGuid);
                if (jobSeeker == null)
                {
                    msg = "User creation process do not completed properly";
                }
                else
                {
                    if (newUser.ChangePassword(resetPwd, newGeneratePass))
                    {
                        isSent = this.SentForgotUserInformation(jobSeeker.Email, newGeneratePass, jobSeeker.Email, out msg);
                    }
                }
            }
            else //Employeer
            {
                if (newUser.ChangePassword(resetPwd, newGeneratePass))
                {
                    Employeer emp = GetEmployeer(useGuid);
                    if (emp == null)
                    {
                        msg = "User creation process do not completed properly";
                    }
                    else
                    {
                        emp.Password = newGeneratePass;

                        ProcessInserEmployeer employeerinsert = new ProcessInserEmployeer();
                        employeerinsert.Employeer = emp;
                        employeerinsert.Update();
                        //Send Emailing...
                        isSent = this.SentForgotUserInformation(emp.Email, newGeneratePass, emp.Email, out msg);
                    }
                }
            }
        }
        if (isSent)
        {
            pnlSuccess.Visible = true;
            lblSuccess.Text = "Password have been sent to the " + txtEmailAddress.Text.Trim() + "!<br>To login your account <a href='Default.aspx'>click here</a>";
        }
        else
        {
            pnlError.Visible = true;
            lblError.Text = msg; // +"<br><br><a href='javascript:history.go(-1);'>Back</a>";
        }
    }

    #region GetJobSeeker
    private JobSeeker GetJobSeeker(Guid jobSeekerId)
    {
        JobSeeker jobSeeker = new JobSeeker();
        ProcessSelectJobSeeker selectJobSeeker = new ProcessSelectJobSeeker();

        selectJobSeeker.JobSeekerID = jobSeekerId;
        selectJobSeeker.invoke();

        if (selectJobSeeker.JobSeeker != null)
        {
            jobSeeker = selectJobSeeker.JobSeeker.FirstOrDefault();
        }

        return jobSeeker;
    }
    #endregion

    #region GetEmployeer
    private Employeer GetEmployeer(Guid employeerId)
    {
        Employeer employeer = new Employeer();
        ProcessSelectEmployeer selectEmployeer = new ProcessSelectEmployeer();

        selectEmployeer.employeerID = employeerId;
        selectEmployeer.invoke();

        if (selectEmployeer.Employeer != null)
        {
            employeer = selectEmployeer.Employeer.FirstOrDefault();
        }

        return employeer;
    }
    #endregion

    private static string GetMailBody()
    {
        string domainName = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + HttpContext.Current.Request.ApplicationPath;
        StringBuilder sb = new StringBuilder();
        try
        {
            using (StreamReader sr = new StreamReader(HttpContext.Current.Server.MapPath("/Resources//ForgotMail.txt")))
            {
                String line = sr.ReadToEnd();
                sb.Append(line);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("The file could not be read:");
            Console.WriteLine(e.Message);
        }
        return sb.ToString();
    }

    private bool SentForgotUserInformation(string userName, string password, string toAddress, out string msg)
    {
        msg = string.Empty;
        bool flag = true;
        try
        {
            //var fromAddress = WebConfigurationManager.AppSettings["EMAIL_FROM_ADDRESS"];
            //var fromPassword = WebConfigurationManager.AppSettings["EMAIL_FROM_PASSWORD"];
            //var smtpAddress = WebConfigurationManager.AppSettings["SMTP_ADDRESS"];
            //var smtPort = WebConfigurationManager.AppSettings["SMTP_PORT"];
            //string body = GetMailBody().Replace("<%USER_NAME%>", userName).Replace("<%PASSWORD%>", password);
            string logo_link = "http://www.npljobs.com/Images/npljobs.jpg";
            string body = GetMailBody().Replace("<%NPL_LOGO%>", logo_link).Replace("<%USER_NAME%>", userName).Replace("<%PASSWORD%>", password);

            //System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient();
            //smtp.Host = smtpAddress;
            //smtp.Port = Convert.ToInt32(smtPort);
            //smtp.UseDefaultCredentials = false;
            //smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
            //smtp.Credentials = new System.Net.NetworkCredential(fromAddress, fromPassword);
            //smtp.EnableSsl = false;
            //smtp.Send(fromAddress, toAddress, subject, body);
            Configuration webConfig = WebConfigurationManager.OpenWebConfiguration("~");
            MailSettingsSectionGroup mailSettings = (MailSettingsSectionGroup)webConfig.GetSectionGroup("system.net/mailSettings");

            if (mailSettings != null)
            {
                string email = mailSettings.Smtp.From;
                string _password = mailSettings.Smtp.Network.Password;
                string emailTo = userName;
                string subject = "Forgotten password retrieval";

                using (MailMessage mail = new MailMessage())
                {
                    mail.From = new MailAddress(email);
                    mail.To.Add(emailTo);
                    mail.Subject = subject;
                    mail.Body = body;
                    mail.IsBodyHtml = true;
                    // Can set to false, if you are sending pure text.

                    using (SmtpClient smtpClient = new SmtpClient(mailSettings.Smtp.Network.Host, mailSettings.Smtp.Network.Port))
                    {
                        smtpClient.Credentials = new NetworkCredential(email, _password);
                        smtpClient.EnableSsl = false;
                        smtpClient.Send(mail);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            msg = ex.Message;
            flag = false;
        }
        return flag;
    }
}